package cn.bnjy.task;

import cn.bnjy.common.EasyData;
import cn.bnjy.entity.Config;
import cn.bnjy.service.IConfigService;
import cn.bnjy.util.CollectionUtils;
import cn.bnjy.util.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 描述：定时更新config表数据
 *
 * @since: 2018/12/15 16:03
 * @author: chavin
 */
@Component
@Slf4j
public class ConfigTask {

    @Autowired
    private IConfigService configService;

    @Scheduled(cron = "0 0/2 * * * *")
    public void createAccessToken( ){
        log.info("自动执行开始：更新config表数据，当前时间：", DateUtils.getDateStr(new Date(), null));
        LocalDateTime startTime = LocalDateTime.now();
        QueryWrapper<Config> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("flush", "1");
        List<Config> list = configService.list(queryWrapper);
        if(CollectionUtils.isNotBlankList(list)) {
            Map<String, String> configMap = EasyData.CONFIG_MAP;
            list.forEach(e -> {
                configMap.put(e.getCKey(), e.getCValue());
                Config config = new Config();
                config.setId(e.getId());
                config.setFlush(0);
                configService.updateById(config);
                log.info("更新config表，key:{}，value:{}", e.getCKey(), e.getCValue());
            });
        }
        LocalDateTime endTime = LocalDateTime.now();
        long time = ChronoUnit.MILLIS.between(startTime, endTime);
        log.info("自动执行结束：更新config表数据，当前时间：" + DateUtils.getDateStr(new Date(), null) + "，耗时：{}ms", time);
    }

}
